#!/bin/bash

CLK=$(getconf CLK_TCK)
path=/proc/stat

echo $path
echo "CLK: ${CLK}"

line=$(head -n1 ${path})
#old=$(awk '{printf "%lu", $14 + $15 + $43}' ${path})
old_sys_irq=$(echo ${line} | awk '{print $7}')
old_sys_sirq=$(echo ${line} | awk '{print $8}')
old_sys=$(echo ${line} | awk '{printf $4}')
old=$((old_sys + old_sys_irq + old_sys_sirq))
t_old=$(echo ${line} | awk '{printf "%lu", $4 + $7 + $8 + $5 + $6 +$2 + $3 + $9}')
while true
do
        times=$(date +"%Y-%m-%d-%T")
        line=$(head -n1 ${path})
        now_sys_irq=$(echo ${line} | awk '{print $7}')
        now_sys_sirq=$(echo ${line} | awk '{print $8}')
        now_sys=$(echo ${line} | awk '{printf $4}')
        now=$((now_sys + now_sys_irq + now_sys_sirq))
        #now=$(awk '{printf "%lu", $14 + $15 + $43}' ${path})
        t_now=$(echo ${line} | awk '{printf "%lu", $4 + $7 + $8 + $5 + $6 +$2 + $3 + $9}')
        delta=$(echo "$now - $old" | bc)
        t_delta=$(echo "${t_now} - ${t_old}" | bc)
        usage=$(echo "scale=2; $delta * 100 / ${t_delta}" | bc)
        sys_delta=$(echo "scale=2;(${now_sys} - ${old_sys}) / ${delta}" | bc)
        sys_irq_delta=$(echo "scale=2;(${now_sys_irq} - ${old_sys_irq}) / ${delta}" | bc)
        sys_sirq_delta=$(echo "scale=2;(${now_sys_sirq} - ${old_sys_sirq}) / ${delta}" | bc)

        echo "${times} CPU sys usage: ${usage}%, sys: ${sys_delta}, irq: ${sys_irq_delta}, sirq: ${sys_sirq_delta}"
        old=$now
        old_sys_irq=${now_sys_irq}
        old_sys_sirq=${now_sys_sirq}
        old_sys=${now_sys}
        t_old=${t_now}

        sleep 1
done

